package com.workingpub.commons.jdbc.builder.ognl;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.util.Assert;

/**
 * OGNL表达式解析计算
 * 
 * @author taoping
 *
 */
public class OgnlEvaluator {

	private OgnlEvaluator() {

	}

	public static boolean evaluateBoolean(String expression, Object rootParam) {
		return evaluateBoolean(expression, rootParam, null);
	}

	public static boolean evaluateBoolean(String expression, Object rootParam, Map<String, Object> others) {
		Object value = OgnlCache.getValue(expression, rootParam, others);
		if (value instanceof Boolean) {
			return (Boolean) value;
		}
		if (value instanceof Number) {
			return !(new BigDecimal(String.valueOf(value)).equals(BigDecimal.ZERO));
		}
		return Boolean.valueOf(String.valueOf(value));
	}

	public static Iterable<?> evaluateIterable(String expression, Object rootParam) {
		return evaluateIterable(expression, rootParam, null);
	}

	public static Iterable<?> evaluateIterable(String expression, Object rootParam, Map<String, Object> otherParams) {
		Object value = OgnlCache.getValue(expression, rootParam, otherParams);
		Assert.notNull(value, "The expression '" + expression + "' evaluated to a null value.");
		if (value instanceof Iterable) {
			return (Iterable<?>) value;
		}
		if (value.getClass().isArray()) {
			int size = Array.getLength(value);
			List<Object> answer = new ArrayList<Object>();
			for (int i = 0; i < size; i++) {
				Object o = Array.get(value, i);
				answer.add(o);
			}
			return answer;
		}
		if (value instanceof Map) {
			return ((Map<?, ?>) value).entrySet();
		}
		throw new IllegalArgumentException(
				"Error evaluating expression '" + expression + "'.  Return value (" + value + ") was not iterable.");
	}
}
